<template>
  <!-- LoginPhone 获取手机号 -->
  <PageContainer>
    <view class="container">
      <Header title="会员登录" :is-custom-back="isFromStartPage || isBackHome" @go-back="goBack" />
      <TImage
        :src="getLogo"
        width="200rpx"
        height="200rpx"
        mode="scaleToFill"
        background-color="#fff"
      />
      <view class="org-name">{{ getName }}</view>

      <view class="btn-box">
        <button
          class="phone-btn"
          type="none"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        >
          微信快捷登录
        </button>
        <!-- <button v-else class="phone-btn" type="none" @click="showToast">微信快捷登录</button>
        <view class="agreement" @click="isAgreest = !isAgreest">
          <image
            v-if="isAgreest"
            class="select-icon"
            src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/card/selected-icon.png"
            mode="scaleToFill"
          />
          <image
            v-else
            class="select-icon"
            src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/card/select-icon.png"
            mode="scaleToFill"
          />
          <text>
            我已阅读并同意
            <text
              class="blue"
              @click.stop="navigateTo({ name: 'userAgreement', options: { type: 1 } })"
            >
              《用户服务协议及隐私政策》
            </text>
          </text>
        </view> -->
      </view>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { navigateBack, navigateTo, onLoad, switchTab } from '@/router';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { computed, ref, unref } from 'vue';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import TImage from '@/components/TImage/index.vue';
  import { ThridTypeEnum } from '@/enums/loginEnum';
  import { getWebAuthUrl } from '@/api/login';
  import type { LoginPhone } from '@/router/types/modules';
  import { TabbarPageEnum } from '@/enums/pageEnum';
  import { Pages } from '@/router/types/pages';
  import { Toast } from '@/utils';
  import { onUnload } from '@dcloudio/uni-app';

  /**  LoginPhone  获取手机号 */
  const isAgreest = ref(false);

  const useUser = useUserStoreWithOut();
  let success: LoginPhone['success'];
  const isBackHome = ref();
  const { globalConfig } = useAppStoreWithOut();
  const getLogo = computed(() => globalConfig?.logo);
  const getName = computed(() => globalConfig?.name);
  const isLoading = ref(false);
  const isFromStartPage = ref(false);
  const androidBack = ref(true);

  async function getPhoneNumber({ detail: { code, iv, encryptedData, errno } }: any) {
    if (errno === 1400001) {
      Toast('手机号授权登录受限,请联系管理员处理');
      return;
    }
    if (!iv || !encryptedData) return;
    if (unref(isLoading)) return;
    isLoading.value = true;
    isBackHome.value = false;
    androidBack.value = false;
    try {
      const { isOfficialAccount } = await useUser.getPhoneNumber({
        code,
        iv,
        encryptedData,
        thridType: ThridTypeEnum.WX3RD,
      });
      // if (isOfficialAccount === IsOfficialAccountEnum.UNKNOWN) {
      //   toAuth().then(navBack);
      // } else {
      //   navBack();
      // }
      navBack();
    } catch (error) {
      isLoading.value = false;
      androidBack.value = true;
    }
  }

  function showToast() {
    uni.showModal({
      title: '服务协议及隐私政策',
      content: `请你务必审慎阅读、充分理解用户协议和隐私政策各条款,包括但不限于用户注意事项、用户行为规范以及为了向你提供服务而收集、使用、存储你个人信息的情况等。你可阅读《用户服务协议及隐私政策》了解详细信息。如你同意,请点击下方按钮开始接受我们的服务。`,
      success: ({ confirm }) => {
        if (confirm) {
          isAgreest.value = true;
        }
      },
    });
  }

  async function toAuth() {
    return new Promise(async (resolve, reject) => {
      const url = await getWebAuthUrl();
      if (url) {
        uni.showLoading({ title: '登录中...', mask: true });
        navigateTo({
          name: 'webview',
          options: {
            url: url,
            title: '公众号授权中...',
            unLoadCallback: () => {
              uni.hideLoading();
              resolve(true);
            },
          },
        });
        return;
      } else {
        resolve(true);
      }
    });
  }

  function navBack() {
    success();
    navigateBack();
  }

  onLoad<'LoginPhone'>((op) => {
    success = op.success;
    isBackHome.value = op.isBackHome;
    const pages = getCurrentPages();
    if (pages[0].route === Pages.startPage) isFromStartPage.value = true;
  });

  function goBack() {
    androidBack.value = false;
    switchTab(TabbarPageEnum.BASE_HOME);
  }

  onUnload(() => {
    if (androidBack.value && isBackHome.value) goBack();
  });
</script>

<style lang="scss" scoped>
  .uni-button {
    border: 0;
  }
  .container {
    height: 100vh;
    display: flex;
    align-items: center;
    // justify-content: center;
    padding-top: 200rpx;
    flex-direction: column;
    background-color: #fff;
  }
  .org-name {
    color: #333;
    font-weight: bolder;
    font-size: 40rpx;
    text-align: center;
    margin-top: 20rpx;
  }

  .btn-box {
    margin-top: 300rpx;
    width: 100%;
    .agreement {
      margin-top: 40rpx;
      font-size: 24rpx;
      color: #333;
      display: flex;
      align-items: center;
      justify-content: center;
      .select-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 10rpx;
      }
      .blue {
        color: #2878ff;
      }
    }
    .phone-btn {
      width: calc(100% - 60rpx);
      height: 96rpx;
      background-color: #e9e3b5;
      color: #333;
      font-size: 32rpx;
      border-radius: 20rpx;
      line-height: 96rpx;
      margin: 0 auto;
    }
    .phone-btn[disabled] {
      opacity: 0.6;
    }
  }
</style>
